<template>
  <!--搜索-->
  <el-form class="query-container" ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
    <el-form-item label="订单号" prop="id">
      <el-input
          v-model="queryParams.id"
          clearable
          placeholder="请输入订单号"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="用户ID" prop="userId">
      <el-input
          v-model="queryParams.userId"
          clearable
          placeholder="请输入用户ID"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <div class="inner-container">
    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="showEditDialog" :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleDelete(null)" :disabled="!selectedIds.length">删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="warning" plain @click="handleExport">导出</el-button>-->
<!--      </el-col>-->
    </el-row>
<!--显示订单信息表-->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30"/>

      <el-table-column prop="id" label="订单号" width="160px"/>
<!--      <el-table-column prop="orderId" label="订单号" width="160px" show-overflow-tooltip/>-->
      <el-table-column prop="createTime" label="创建时间" width="160px" show-overflow-tooltip/>
      <el-table-column prop="orderStatus" label="订单状态" :formatter="orderStatusFormatter" show-overflow-tooltip/>
      <el-table-column prop="userId" label="用户ID" show-overflow-tooltip/>
      <el-table-column prop="vehicleId" label="车辆ID" show-overflow-tooltip/>
      <el-table-column prop="addr" label="取车地址" :formatter="addrTypeFormatter" show-overflow-tooltip/>
      <el-table-column prop="startDate" label="取车时间" show-overflow-tooltip/>
      <el-table-column prop="endDate" label="还车时间" show-overflow-tooltip/>
      <el-table-column prop="rentalDuration" label="租车时长" show-overflow-tooltip/>
      <el-table-column prop="totalCost" label="金额" show-overflow-tooltip  width="60px"/>
      <el-table-column prop="paymentStatus" label="支付状态" :formatter="payStatusFormatter" show-overflow-tooltip/>
      <el-table-column prop="paymentMethod" label="支付方式" :formatter="payWayStatusFormatter" show-overflow-tooltip width="100px"/>
      <el-table-column prop="paymentDate" label="支付时间" show-overflow-tooltip/>
      <el-table-column prop="cancellationTime" label="撤单时间" show-overflow-tooltip/>
      <el-table-column prop="couponType" label="优惠类型" show-overflow-tooltip :formatter="couponTypeFormatter"/>

      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="showEditDialog(scope.row)">修改</el-button>
          <el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <!--Element UI 提供的分页组件-->
    <el-pagination
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    <!--新增、修改订单弹窗-->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" append-to-body>
      <el-form ref="dialogFormRef" :model="formData" :rules="formRules" label-width="100px">

        <el-form-item label="订单号" prop="id" style="width:50%;" >
          <el-input readonly v-model="formData.id" placeholder="无需填写，将由系统生成"/>
        </el-form-item>
        <el-form-item label="订单状态"  prop="orderStatus" style="width:30%;">
          <el-select v-model="formData.orderStatus" placeholder="请选择订单状态" style="width:96%;">
            <el-option value="0" label="已取消"></el-option>
            <el-option value="1" label="进行中"></el-option>
            <el-option value="2" label="已完成"></el-option>
            <el-option value="3" label="待支付"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID" prop="userId" style="width:50%;">
          <el-input v-model="formData.userId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="车辆ID" prop="vehicleId" style="width:50%;">
          <el-input v-model="formData.vehicleId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="取车地"  prop="addr" style="width:30%;">
          <el-select v-model="formData.addr" placeholder="请选择门店" style="width:96%;" :formatter="addrFormatter">
            <el-option value="1" label="西乡塘"></el-option>
            <el-option value="2" label="良庆"></el-option>
            <el-option value="3" label="兴宁"></el-option>
            <el-option value="4" label="江南"></el-option>
            <el-option value="5" label="青秀"></el-option>
            <el-option value="6" label="邕宁"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租车时段" style="width:70%;">
          <el-date-picker
              type="datetimerange"
              range-separator="至"
              start-placeholder="取车时间"
              end-placeholder="还车时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="times"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="金额" prop="totalCost" style="width:50%;">
          <el-input v-model="formData.totalCost" placeholder="请输入金额"/>
        </el-form-item>
        <el-radio-group v-model="formData.paymentMethod">
          <!-- value控制当前选项被选中时提交的值 label控制选项上显示的文字 -->
          <el-form-item label="支付方式" >
            <el-radio value="11" label="微信支付"></el-radio>
            <el-radio value="22" label="支付宝支付"></el-radio>
          </el-form-item>
        </el-radio-group>

      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>
    <!--弹窗结束-->
  </div>

</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'

// --------------------------------------------------

const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({pageNum: 1, pageSize: 10})
const total = ref(0)
const tableData = ref([])
const selectedIds = ref([])

// 获取订单数据
const listData = () => {
  loading.value = true
  request.get('/api/bus/order', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    tableData.value = res.data.list
    loading.value = false
  })
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}

//删除订单
const handleDelete = (row) => {
  let ids = row ? [row.id] : [...selectedIds.value]
  if (ids.length === 0) {
    ElMessage.error('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete(`/api/bus/order?ids=${ids}`)
        .then(res => {
          selectedIds.value.length = 0
          listData()
          ElMessage.success('删除成功')
        })
  }).catch(() => {})
}
// --------------------------------------------------

//定义变量用来保存起止时间
const times = ref([]);

const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const formData = ref({
  id: undefined,
  orderStatus: undefined,
  userId: undefined,
  vehicleId: undefined,
  addr: undefined,
  totalCost: undefined,
  paymentMethod: undefined,
})

const formRules = ref({
  // id: [{required: true, message: '订单号为必填项'}],
  // orderStatus: [{required: true, message: '订单状态为必填项'}],
})
const showAddDialog = () => {
  dialogTitle.value = '新增订单'
  dialogVisible.value = true
}
// 修改订单
const showEditDialog = (row) => {
  let id = row.id || selectedIds.value
  request.get(`/api/bus/order/${id}`)
      .then(res => {
        times.value = [res.data.startDate, res.data.endDate];
        formData.value = res.data
        dialogTitle.value = '修改订单信息'
        dialogVisible.value = true
      })
}
const closeDialog = () => {
  formData.value = {
    id: undefined,
    // orderId: undefined,
    orderStatus: undefined,

  }
  dialogFormRef.value.resetFields()
  dialogVisible.value = false
}

const saveOrUpdate = () => {
  formData.value.startDate = times.value[0]; // 设置开始时间
  formData.value.endDate = times.value[1]; // 设置结束时间
  dialogFormRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数');
      return;
    }
    const id = formData.value.id;
    request({
      url: '/api/bus/order',
      method: id ? 'put' : 'post',
      data: formData.value
    }).then(res => {
      closeDialog();
      listData();
      ElMessage.success(id ? '修改成功' : '新增成功');
    });
  });
};

//加载数据
onMounted(() => {
  listData()
})


//订单状态显示转换
const orderStatusFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '已取消';
  }else if (cellValue==1){
    cellValue = '进行中';
  }else if (cellValue==2){
    cellValue = '已完成';
  }else if (cellValue==3){
    cellValue = '待支付';
  }
  return cellValue;
}

//支付方式显示转换
const payWayStatusFormatter = (row,column,cellValue,index)=>{
  if (cellValue==11){
    cellValue = '微信支付';
  }else if (cellValue==22){
    cellValue = '支付宝支付';
  }
  return cellValue;
}

//支付状态显示转换
const payStatusFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '未支付';
  }else if (cellValue==1){
    cellValue = '已支付';
  }else if (cellValue==2){
    cellValue = '支付失败';
  }
  return cellValue;
}

//优惠类型显示转换
const couponTypeFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '暂无';
  }else if (cellValue==30){
    cellValue = '商家优惠券';
  }else if (cellValue==40){
    cellValue = '平台优惠券';
  }
  return cellValue;
}

//地址类型显示转换
const addrTypeFormatter = (row,column,cellValue,index)=>{
  if (cellValue==1){
    cellValue = '西乡塘';
  }else if (cellValue==2){
    cellValue = '良庆';
  }else if (cellValue==3){
    cellValue = '兴宁';
  }
  else if (cellValue==4){
    cellValue = '江南';
  }
  else if (cellValue==5){
    cellValue = '青秀';
  }
  else if (cellValue==6){
    cellValue = '邕宁';
  }
  return cellValue;
}

</script>

<style scoped>

</style>
